﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using NBlock.Core;
using NBlock.Core.ORM;
using NBlock.Core.ORM.EF;
using NBlock.MVCExtensions;
using Ninject;
using Cost.Services;
using Cost.Models;

namespace Cost.Controllers
{
    public class OrgController : Controller
    {
        #region 构造函数
        OrgService _OrgService = null;
        ICostRepository<Organization> _Repo;
        ICostRepository<UserInfo> _RepoUser;
        public OrgController(ICostRepository<Organization> repo,
            OrgService orgService,
            ICostRepository<UserInfo> repoUser)
        {
            _Repo = repo;
            _OrgService = orgService;
            _RepoUser = repoUser;
        }
        #endregion

        public ActionResult Index()
        {
            // 默认选中第一个节点
            ViewBag.DefaultNodeid = _Repo.FindAll().OrderBy(o => o.FullPath.Length).Select(o => o.Id).FirstOrDefault();
            return View();
        }

        public ActionResult Edit(string Id, string parentId)
        {
            var data = _OrgService.GetOrg(Id, parentId);
            return View(data);
        }

        [HttpPost]
        public JsonResult Save(string Id)
        {
            var data = _Repo.Find(Id) ?? new Organization();
            TryUpdateModel(data);
            _OrgService.SaveOrg(data);
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult Delete(string Id)
        {
            _Repo.Delete(Id);
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult DeleteAll(string Ids)
        {
            var items = Ids.Split(',');
            _Repo.DeleteAll(d => items.Contains(d.Id));
            return Json(nbAjaxMessage.Successful);
        }

        [HttpPost]
        public JsonResult List(string parentId, nbPageInfo pager, nbSearchCondition where)
        {
            var pageData = _Repo.GetPageable(pager, o => o.ParentId == parentId, where);
            return Json(pager.ToGridData(pageData));
        }

        [HttpPost]
        public JsonResult Tree(string Id)
        {
            var orgs = _OrgService.GetOrgsByParentId(Id);
            var treeData = CommonLogic.GetSubOrgTree(Id, orgs);
            return Json(treeData);
        }

        public JsonResult ValidOrgCode(string Id, string OrgCode)
        {
            var result = _OrgService.IsValidCode(Id, OrgCode);
            return Json(result, JsonRequestBehavior.AllowGet);
        }

        [HttpPost]
        public JsonResult GetFirstPY(string name)
        {
            var firstPY = string.Empty;
            if (!string.IsNullOrWhiteSpace(name))
            {
                firstPY = HZ2PY.GetFirstPY(name);
            }
            return Json(nbAjaxMessage.Successful.SetData(firstPY));
        }

        #region OrgUser（指定部门下的用户列表）
        public ActionResult OrgUser(string orgId)
        {
            ViewBag.OrgId = orgId;
            return View();
        }

        [HttpPost]
        public JsonResult OrgUser(string orgId, nbPageInfo pager, nbSearchCondition where)
        {
            var pageData = _RepoUser.GetPageable(pager, u => u.OrgId == orgId, where);
            return Json(pager.ToGridData(pageData));
        }
        #endregion

        #region SetOrg（选择用户部门）
        public ActionResult SetOrg()
        {
            return View();
        }

        [HttpPost]
        public JsonResult OrgTree(string Id)
        {
            var orgs = _OrgService.GetOrgsByParentId(Id);
            var list = CommonLogic.GetSubOrgTree(Id, orgs);
            return Json(list);
        }
        #endregion

        #region 临时的，用于同步金慧库的组织机构和用户信息
        public ActionResult Sync(string parentId)
        {
            parentId = parentId ?? string.Empty;
            var orgs = _OrgService.GetOrgsByParentId(parentId);
            SyncSubOrg(parentId, orgs);
            return Content("操作成功了！");
        }

        private void SyncSubOrg(string parentId, IList<Organization> orgs)
        {
            parentId = parentId ?? string.Empty;
            var list = new List<nbJsonTreeNode>();
            foreach (var org in orgs.Where(o => o.ParentId == parentId))
            {
                // 处理全路径和部门编号
                org.OrgCode = HZ2PY.GetFirstPY(org.OrgName);
                var count = _Repo.FindAll(o => o.OrgCode.StartsWith(org.OrgCode) && o.Id != org.Id).Count();
                if (count > 0)
                    org.OrgCode = org.OrgCode + count.ToString();

                // 处理父节点，如果是根节点，则为空字符串
                org.ParentId = org.ParentId ?? string.Empty;
                org.ParentCode = org.ParentCode ?? string.Empty;
                org.ParentName = org.ParentName ?? string.Empty;
                _Repo.Update(org);
                _Repo.Commit();

                SyncSubOrg(org.Id, orgs);
            }
        }
        #endregion
    }
}
